package com.microservice.base.task;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jbx
 * @package_name com.microservice.base.task
 * @create_date 2020/12/10 15:17
 */
public class testbase64 {
  public static void main(String[] args) {
    String imageStr =
        getImgUrlToBase64(
            "http://ms.do-ok.com:18010/file/3306812001/user/0f190ff3a0264e1e968605288a517d418.jpg");
    System.out.println(imageStr);
    base64StrToImage(imageStr, "D:/imagebase/1.jpg");
  }

  public static byte[] compressUnderSize(byte[] srcImgData, long maxSize) {
    double scale = 0.9;
    byte[] imgData = Arrays.copyOf(srcImgData, srcImgData.length);

    if (imgData.length > maxSize) {
      do {
        try {
          imgData = compress(imgData, scale);

        } catch (IOException e) {
          throw new IllegalStateException("压缩图片过程中出错，请及时联系管理员！", e);
        }

      } while (imgData.length > maxSize);
    }

    return imgData;
  }
  public static byte[] compress(byte[] srcImgData, double scale) throws IOException {
    BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData));
    int width = (int) (bi.getWidth() * scale); // 源图宽度
    int height = (int) (bi.getHeight() * scale); // 源图高度

    Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);
    BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics g = tag.getGraphics();
    g.setColor(Color.RED);
    g.drawImage(image, 0, 0, null); // 绘制处理后的图
    g.dispose();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ImageIO.write(tag, "JPG", bOut);

    return bOut.toByteArray();
  }
  /**
   * base64编码字符串转换为图片
   *
   * @param imgStr base64编码字符串
   * @param path 图片路径
   * @return
   */
  public static boolean base64StrToImage(String imgStr, String path) {
    if (imgStr == null) {
      return false;
    }
    BASE64Decoder decoder = new BASE64Decoder();
    try {
      // 解密
      byte[] b = decoder.decodeBuffer(imgStr);
      // 处理数据
      for (int i = 0; i < b.length; ++i) {
        if (b[i] < 0) {
          b[i] += 256;
        }
      }
      // 文件夹不存在则自动创建
      File tempFile = new File(path);
      if (!tempFile.getParentFile().exists()) {
        tempFile.getParentFile().mkdirs();
      }
      OutputStream out = new FileOutputStream(tempFile);
      out.write(b);
      out.flush();
      out.close();
      return true;
    } catch (Exception e) {
      return false;
    }
  }

  /**
   * 将网络图片转换成Base64编码字符串
   *
   * @param imgUrl 网络图片Url
   * @return
   */
  public static String getImgUrlToBase64(String imgUrl) {
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;
    byte[] buffer = null;
    try {
      // 创建URL
      URL url = new URL(imgUrl);
      // 创建链接
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setConnectTimeout(5000);
      inputStream = conn.getInputStream();
      outputStream = new ByteArrayOutputStream();
      // 将内容读取内存中
      buffer = new byte[1024];
      int len = -1;
      while ((len = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, len);
      }
      buffer = outputStream.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (inputStream != null) {
        try {
          // 关闭inputStream流
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (outputStream != null) {
        try {
          // 关闭outputStream流
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    // 对字节数组Base64编码
    byte[] images = compressUnderSize(buffer, 200*1024);
    return new BASE64Encoder().encode(images);
  }

  //  @Test
  //  public void testLimit() {
  //    List<Integer> list = new ArrayList();
  //    for (int i = 0; i < 97; i++) {
  //      list.add(i);
  //    }
  //    // lamdba式的强大之处
  //    for (int j = 0; j <= list.size() / 10; j++) {
  //      //      List<Integer> collect1 =
  //      // list.stream().skip(10*j).limit(10).collect(Collectors.toList());
  //      //      for (Integer integer : collect1) {
  //      //        System.out.println(integer);
  //      //      }
  //      for (int i = 0; i < 10; i++) {
  //        System.out.println(list.get(i + 10 * j));
  //      }
  //      System.out.println("第" + j + "次================================");
  //    }
  //  }

  //  @Test
  //  public void httpposttest() {
  //    String[] strings = new String[2];
  //    JSONObject jo = new JSONObject();
  ////    String ss = "00dfbd32eaa74758917e963a578c34a6";
  //    strings[0] = "033227523f9944e09c3eda01bc651303";
  //    strings[1] = "03d8a23a16ee4b4d87b004129b2afe3b";
  //    jo.put("userId", strings);
  //    System.out.println(jo);
  //    String s = HttpClientUtil.HttpPostWithJson(
  //            "http://ms.do-ok.com:18010/inner/menu/v1/getMenuListByUserId", jo.toString());
  //    System.out.println(s);
  //  }

}
